package tpase.client.Handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import tpase.client.VO.FileInfo;
import tpase.client.VO.Message;
import tpase.client.VO.StatusCode;
import tpase.util.Util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ClientQueryFileInfoHandler extends ChannelInboundHandlerAdapter {

    private String uid;
    private List<FileInfo> fileInfoList;

    public ClientQueryFileInfoHandler(String uid, List<FileInfo> fileInfoList) {
        this.uid = uid;
        this.fileInfoList = fileInfoList;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Message request = new Message(StatusCode.QUERY_FILE_REQUEST);
        Map<String, byte[]> map = request.getMap();
        map.put("uid", uid.getBytes());

        ctx.writeAndFlush(request);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Message respond = (Message) msg;
        int statusCode = respond.getStatusCode();
        if (statusCode == StatusCode.QUERY_FILE_RESPONSE) {
            List<FileInfo> fileInfoList1 = Util.jsonToObject(new String(respond.getMap().get("fileInfoList")), ArrayList.class, FileInfo.class) ;
            fileInfoList.addAll(fileInfoList1);
        }
        ctx.close();
    }




    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("ClientQueryFileInfoHandler: 发生异常，关闭通道");
        System.out.println(cause.toString());
        ctx.close();
    }
}
